import 'dart:math' as math;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter/material.dart';
import 'package:iea/models/paidCauserDetail_models/detail_picBar_model.dart'; 
class SubList extends StatefulWidget{
  final goodsDetail;
  final subListKey;
  SubList({Key key, this.goodsDetail, this.subListKey}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _SubListState();
}

class _SubListState extends State<SubList>
  with AutomaticKeepAliveClientMixin<SubList> {
  @override
  bool get wantKeepAlive => true;
  ScrollController _controller = new ScrollController();
  int rowListItemIndex = 0;
  bool isOpen = false;
  List courseModuleList = [];
  List lessonList = [];
  _subList(bool isOpen) {
    CourseModuleList lesson = courseModuleList[rowListItemIndex];
    if (isOpen) {
      lessonList = lesson.lessonList;
    } else {
      lessonList = lesson.lessonList.length > 4 ? lesson.lessonList.sublist(0, 4) : lesson.lessonList;
    }
  }
  @override
  void initState() {
    super.initState();
    courseModuleList = widget.goodsDetail.courseModuleList;
    rowListItemIndex = widget.goodsDetail.openModuleIndex;
    _subList(isOpen);
  }
  @override
  void didChangeDependencies() {
    WidgetsBinding.instance.addPostFrameCallback(_onAfterRendering);
    super.didChangeDependencies();
  }
  void _onAfterRendering(Duration timeStamp){
    print(rowListItemIndex);
    _controller.animateTo(151.00 * rowListItemIndex,
      duration: Duration(milliseconds: 200),
      curve: Curves.ease
    );
  }
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context){
    super.build(context);
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);
    return SliverToBoxAdapter(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Column(
            key: widget.subListKey,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: ScreenUtil().setWidth(375),
                padding: EdgeInsets.only(top: 6,left: 15.0),
                decoration: BoxDecoration(
                  border: Border(top: BorderSide(color: Color.fromRGBO(247, 247, 247, 1), width: 6.0))
                ),
                child: Text('全部课时：' + widget.goodsDetail.lessonCount.toString() +'节课（有效期' + widget.goodsDetail.serviceDays.toString() + '天）',
                  style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 13.0, height: 2.0),
                ),
              ),
              Container(
                child:  courseModuleList.length == 1 ? Container() : Container(
                  height: 81.0,
                  margin: EdgeInsets.symmetric(vertical: 12.0),
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    controller: _controller,
                    itemCount: courseModuleList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return rowListItem(courseModuleList[index], index);
                    },
                  ),
                ),
              ),
              Container(
                child: ListView.separated(
                  itemCount: lessonList.length,
                  shrinkWrap: true,
                  physics: ScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return columnListItem(lessonList[index]);
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      height: 1.0,
                      margin: EdgeInsets.only(left: ScreenUtil().setWidth(50)),
                      decoration: BoxDecoration(
                        color: Color.fromRGBO(221, 221, 221, 1),
                      ),
                    );
                  }
                ),
              ),
              Container(
                height: 1.0,
                margin: EdgeInsets.only(left: ScreenUtil().setWidth(50), bottom: 33.0),
                decoration: BoxDecoration(
                  color: lessonList.length > 0 ? Color.fromRGBO(221, 221, 221, 1) : null,
                ),
              ),
              GestureDetector(
                onTap: () {
                  setState(() {
                  isOpen = !isOpen;
                  _subList(isOpen);
                  });
                },
                child: courseModuleList[rowListItemIndex].lessonList.length < 5 ? Text('') : Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(isOpen ? '立即收起 ' : '展开更多 ',
                      style: TextStyle(fontSize: 11.0, color: Color.fromRGBO(255, 93, 0, 1)),
                    ),
                    Container(
                      child: Transform.rotate(
                        angle: isOpen ? math.pi : math.pi * 2,
                        child: Image(
                          image: AssetImage('assets/images/homepage/angle.png'),
                          width: 9.0,
                          height: 5.0,
                          fit: BoxFit.contain,
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                padding: EdgeInsets.all(15.0),
                child: Text('课程介绍',
                  style: TextStyle(fontSize: 19.0, color: Color.fromRGBO(51, 51, 51, 1), fontWeight: FontWeight.bold),
                ),
              ),
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/homepage/bgCourse.png'),
                    fit: BoxFit.cover,
                    alignment: Alignment.topRight
                  )
                ),
                padding: EdgeInsets.all(30.0),
                child: Html(
                  data: widget.goodsDetail.courseContent,
                ),
              )
            ],
          ),
          Container(margin: widget.goodsDetail.bottomStatus == 1 || widget.goodsDetail.bottomStatus == 4 ? EdgeInsets.only(bottom: 52.0) : null),
        ],
      ),
    );
  }
  // 课程列表横向滑动列表
  Widget rowListItem(item, index){
    return GestureDetector(
      onTap: (){
        setState(() {
          rowListItemIndex = index;
          isOpen = false;
          _subList(isOpen);
        });
        _controller.animateTo(151.00 * index,
          duration: Duration(milliseconds: 500),
          curve: Curves.easeOut
        );
      },
      child: Container(
        width: 145.0,
        margin: EdgeInsets.only(top: 12.0, bottom: 12.0, left: 9.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5.0),
          boxShadow: [
            BoxShadow(color: Color.fromRGBO(192, 192, 192, 0.5), blurRadius: 8.0, offset: Offset(3.0, 3.0))
          ],
          image: DecorationImage(
            image: AssetImage(rowListItemIndex == index ? 'assets/images/homepage/detail_subList_check.png' : 'assets/images/homepage/detail_subList_unCheck.png'),
            fit: BoxFit.contain,
          ),
        ),
        child: Row(
          children: <Widget>[
            Container(
              width: 28.0,
              height: 27,
              margin: EdgeInsets.only(left: 9.0),
              child: Text((index + 1).toString(),
                style: TextStyle(fontSize: 16.0, color: rowListItemIndex == index ? Color.fromRGBO(255, 255, 255, 1) : Color.fromRGBO(153, 153, 153, 1), height: 1.2),
                textAlign: TextAlign.center,
              ),
            ),
            Container(
              width: 96.0,
              margin: EdgeInsets.only(left: 10.0),
              child: Text(item.moduleName,
                style: TextStyle(fontSize: 13.0, color: rowListItemIndex == index ? Color.fromRGBO(255, 255, 255, 1) : Color.fromRGBO(153, 153, 153, 1)),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            )
          ],
        ),
      )
    );
  }
  // 课程列表纵线列表
  Widget columnListItem(item) {
    return GestureDetector(
      onTap: () {
        print(item);
      },
      child: Container(
        padding: EdgeInsets.only(left: 15.0, top: 12.0, bottom: 12.0),
        color: Colors.white,
        child: Row(
          children: <Widget>[
            Image(
              image: AssetImage(item.isFree == 1 ? 'assets/images/homepage/detail_subList_unpause.png' : 'assets/images/homepage/detail_subList_lock.png'),
              width: ScreenUtil().setWidth(23),
              height: ScreenUtil().setHeight(23),
              fit: BoxFit.fill,
            ),
            Padding(padding: EdgeInsets.only(right: ScreenUtil().setWidth(20))),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Stack(
                  children: <Widget>[
                    Container(
                      width: ScreenUtil().setWidth(240),
                      child: Text(item.isFree == 1 ? '         ' + item.courseName : item.courseName,
                        style: TextStyle(fontSize: 14.0, color: Color.fromRGBO(51, 51, 51, 1), height: 1.2),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Positioned(
                      top: 8,
                      child: Image(
                        image: AssetImage(item.isFree == 1 ? 'assets/images/homepage/detail_subList_listen.png' : ''),
                        width: ScreenUtil().setWidth(29),
                        height: ScreenUtil().setHeight(10),
                        fit: BoxFit.contain,
                      ),
                    ),
                  ],
                ),
                Padding(padding: EdgeInsets.only(top: 2.0)),
                Row(
                  children: <Widget>[
                    Container(
                      width: 9,
                      height: 10,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage( item.learnRate < 1 ? 'assets/images/homepage/detail_subList_unplay.png' : 'assets/images/homepage/detail_subList_play.png'),
                          fit: BoxFit.contain,
                        )
                      ),
                    ),
                    Padding(padding: EdgeInsets.only(left: 4.0)),
                    Text(item.learnRate < 1 ? '未开始' : '已学习' + item.learnRate.toString() + '%',
                      style: TextStyle(fontSize: 12.0, color: item.learnRate < 1 ? Color.fromRGBO(153, 153, 153, 1) : Color.fromRGBO(243, 110, 34, 1)),
                    )
                  ],
                )
              ],
            ),
            Container(
              width: 1.0,
              height: 28.0,
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(20), right: ScreenUtil().setWidth(10)),
              decoration: BoxDecoration(
                color: Colors.black12,
              ),
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: ScreenUtil().setWidth(32),
                  height: ScreenUtil().setHeight(32),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(ScreenUtil().setWidth(15)),
                    image: DecorationImage(
                      image: NetworkImage(item.teacherAvatarUrl == null ? '' : item.teacherAvatarUrl, scale: 1.0),
                      fit: BoxFit.contain
                    )
                  ),
                ),
                Container(
                  width: ScreenUtil().setWidth(30),
                  child: Text(item.teacherName == null ? '' : item.teacherName,
                    style: TextStyle(fontSize: 10.0, color: Color.fromRGBO(25, 25, 25, 1)),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                )
              ],
            )
          ],
        ),
      )
    );
  }
}